


#include "dbPOS.h"



dbPOS::dbPOS()
{
	mydb = new OTLDatabaseLayer();

}

dbPOS::dbPOS(wxString ip,wxString SID,wxString user, wxString pass)
{
	db_user=user;
	db_pass=pass;
	db_ip=ip;
	db_SID=SID;
	mydb = new OTLDatabaseLayer();

}

dbPOS::~dbPOS()
{
	delete mydb;	
	
}


wxGridTableBase* dbPOS::GetTable(wxString cmd)
{
	DatabaseResultSet* rs;
	//wxGridTableBase* dtb;
	dbTable* dtb;
	try
	{
		if (!mydb->IsOpen())
		{
			mydb->Open(db_ip,db_SID,db_user,db_pass);
		}
	
	rs = mydb->RunQueryWithResults(cmd);
	dtb = new dbTable();
	int cols = rs->GetMetaData()->GetColumnCount();

	
	for(int i=0; i<cols;i++)
	{
		dtb->AppendCols();
		dtb->SetColLabelValue(i,rs->GetMetaData()->GetColumnName(i));
		dtb->SetColType(i, rs->GetMetaData()->GetColumnType(i));
	}
	int row=0;
	
	while(rs->Next())
	{
		
		dtb->AppendRows();
		for(int i=0;i<cols;i++)
		{
			switch(dtb->GetColType(i))
			{	
				case 0:
					{
						dtb->SetValueasNull(row,i);
						break;
					}
				case 1:
					{
						dtb->SetValueasNull(row,i);
						break;
					}
				case 2:
					{
						dtb->SetValue(row,i,wxString::Format(wxT("%d"),rs->GetResultInt(i+1)));
						break;
					}
				case 3:
					{
						
						dtb->SetValue(row,i,rs->GetResultString(i+1));
						
						break;
					}
				case 4:
					{

						dtb->SetValueAsDouble(row,i,rs->GetResultDouble(i+1));	
						break;
					}
				case 5:
					{
						dtb->SetValueAsBool(row,i,rs->GetResultBool(i+1));
						break;
					}
				case 6:
					{
						dtb->SetValue(row,i, wxT("Blob Field"));
						break;
					}
				case 7:
					{
						if (rs->IsFieldNull(i+1))
						{
							dtb->SetValueasNull(row,i);
						}
						else
						{
							if (rs->GetResultDate(i+1).IsValid())
							{
								dtb->SetValue(row,i, rs->GetResultDate(i+1).Format(wxDefaultDateTimeFormat));
								}
							else
							{
								dtb->SetValue(row,i, wxT("Unvalid Date"));
							}
						}
						break;
					}
			}
		}
		row++;
		
	}
	rs->Close();
	//mydb->Close();
	return dtb;
	}
	catch(DatabaseLayerException& ex)
	{
		wxMessageBox(wxT("Data Base Error!")+ ex.GetErrorMessage());
		
		mydb->Close();
		return NULL;

	}
}

bool dbPOS::dbInsert(wxString cmd)
{
	try
	{
		if (!mydb->IsOpen())
		{
			mydb->Open(db_ip,db_SID,db_user,db_pass);
		}
		
		mydb->RunQuery(cmd, false);
		
		mydb->Commit();
		mydb->Close();

		return true;
	}
	catch(DatabaseLayerException& ex)
	{
		mydb->Close();
		wxMessageBox(ex.GetErrorMessage());
		return false;
	}
}






			





